import Vue from 'vue';
import VueRouter from "vue-router";
import Home from "../pages/Home";
import store from '../store'

Vue.use(VueRouter);

const routes = [
    {
        path: '/',
        name: 'home',
        component: Home
    },
    {
        path: '/channel/:id', //变量后+？表示可以变量可以为空
        name: 'channel',
        component: () => import('../pages/ChannelNews')
    },
    {
        path: '/register',
        name: 'register',
        component: () => import('../pages/Register')
    },
    {
        path: '/login',
        name: 'login',
        component: () => import('../pages/Login')
    },
    {
        path: '/setting',
        name: 'setting',
        component: ()=>import('../pages/Setting'),
        meta: {
            auth: true
        }
    },
    {
        path: '/personal',
        name: 'personal',
        component: () => import('../pages/Personal'),
        // 需要鉴权的页面设置 meta
        meta: {
            auth: true
        }
    },
    {
        path: '/auth',
        name: 'auth',
        component: () => import('../pages/Auth'),
    },
    {
        path: '*',
        name: 'notfound',
        component: () => import('../pages/NotFound')
    }
]

// 2、创建路由对象
var router = new VueRouter({
    // 配置
    mode: 'history',
    routes
});
// 处理路由快速点击会报错 === Uncaught (in promise) NavigationDuplicated
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
}


// 注册全局多个页面路由守卫
router.beforeEach((to, from, next) => {
    // 需要登录才能访问
    if (to.meta.auth) {
        // 正在验证中
        if (store.state.loginUser.isLoading) {
            next({name: 'auth', query: {redirect: to.fullPath}})
        } else if (store.state.loginUser.data) {
            // 登录成功，可以访问
            next()
        } else {
            // 未登录
            next({name: 'login'})
        }
        // 不需要登录，直接访问
    } else {
        // 都可以访问
        next()
    }
})

export default router;
